<template>
  <div class="role">
    <page-search
      :search-config="searchConfig"
      @resetClick="handleSearchReset"
      @queryClick="handleSearchQuery"
    />
    <page-content
      :content-config="contentConfig"
      ref="contentRef"
      @createRecord="handleCreateRecord"
      @editRecord="handleEditRecord"
    >
    </page-content>
    <page-modal ref="modalRef" :modal-config="modalConfig" :other-info="otherInfoRef">
      <template #menulist>
        <el-tree
          ref="elTreeRef"
          :data="stateEntireMenus"
          :props="{ children: 'children', label: 'name' }"
          node-key="id"
          show-checkbox
          @check="handleElTreeChecked"
        />
      </template>
    </page-modal>
  </div>
</template>

<script setup lang="ts">
import searchConfig from '@/views/main/system/role/config/search.config';
import contentConfig from '@/views/main/system/role/config/content.config';
import modalConfig from '@/views/main/system/role/config/modal.config';
import usePageContent from '@/hooks/usePageContent';
import usePageModal from '@/hooks/usePageModal';
import { useMainStore } from '@/store/mian';
import { storeToRefs } from 'pinia';
import { ref, nextTick } from 'vue';
import { ElTree } from 'element-plus';
import { mapRoleObjToArray } from '@/utils/map-menus';

const { contentRef, handleSearchReset, handleSearchQuery } = usePageContent();
const { modalRef, handleCreateRecord, handleEditRecord } = usePageModal(
  editRoleClickCallback,
  createRoleClickCallback
);

const mainStore = useMainStore();
const { stateEntireMenus } = storeToRefs(mainStore);
const otherInfoRef = ref({});

interface ICheckInfo {
  checkedNodes: any[];
  checkedKeys: any[];
  halfCheckedKeys: any[];
  halfCheckedNodes: any[];
}

/**
 * @function handleElTreeChecked 当前角色的菜单树被选中时触发
 * @param data1 回调参数
 * @param data2 回调参数
 */
function handleElTreeChecked(data1: any, data2: ICheckInfo) {
  const menuList = [...data2.checkedKeys, ...data2.halfCheckedKeys];
  otherInfoRef.value = { menuList };
  console.log('menuList', menuList);
}

/** 获取到到el-tree的实例，方便调用其中的方法为其设置值 */
const elTreeRef = ref<InstanceType<typeof ElTree>>();

/**
 * @function editRoleClickCallback 编辑角色时，获取到角色的菜单列表，将其设置到el-tree中
 * @param recordData
 */
function editRoleClickCallback(recordData: any) {
  /** 因为在表格中的数据是对象，而el-tree需要的是数组，所以需要将其转换为数组 */
  const menuList = mapRoleObjToArray(recordData.menuList);
  /** nextTick() 用来在DOM更新后执行回调函数 */
  nextTick(() => {
    elTreeRef.value?.setCheckedKeys(menuList);
  });
}

/**
 * @function createRoleClickCallback 创建角色时，清空el-tree中的值
 */
function createRoleClickCallback() {
  nextTick(() => {
    elTreeRef.value?.setCheckedKeys([]);
  });
}
</script>

<style scoped lang="scss">
.role {
}
</style>
